package org.gikolet.ch2.android.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.gikolet.ch2.data.Board;
import org.gikolet.ch2.data.ThreadHeader;
import org.gikolet.ch2.io.Parser;
import org.gikolet.ch2.io.Storage;
import org.gikolet.ch2.io.ThreadHeadersReader;

public class LocalSubjectReader implements ThreadHeadersReader {

	private Board board;
	private BufferedReader reader;
	private Parser<ThreadHeader> parser;

	public LocalSubjectReader(Board board, Storage storage,
			Parser<ThreadHeader> parser, String charsetName)
			throws FileNotFoundException {
		this(board, storage, parser, Charset.forName(charsetName));
	}

	public LocalSubjectReader(Board board, Storage storage,
			Parser<ThreadHeader> parser, Charset charset)
			throws FileNotFoundException {

		this.board = board;
		this.parser = parser;

		File file = null;

		try {
			file = new File(storage.getDirectoryAndCreate(board), "subject.txt");

		} catch (IOException e) {
			e.printStackTrace();
		}

		if (file != null) {
			this.reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), charset));
		}
	}

	public ThreadHeader read() throws IOException {
		ThreadHeader s = null;

		String line = this.reader.readLine();
		if (line != null) {
			s = this.parser.parse(line);
			s.setBoard(this.board);
		}
		return s;
	}

	public void close() throws IOException {
		this.reader.close();
	}
}
